package frame;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Vector;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

import dao.CourseDao;
import dao.ScoreDao;
import dao.StudentDao;
import model.Course;
import model.Score;
import model.Student;



public class ScorePanel extends CommonPanel {

    private Vector columns;

    private Box center = Box.createHorizontalBox();
    //学生下拉框
    //JComboBox studentComboBox;

    //课程下拉框
    //JComboBox courseComboBox;

    //学号
    JTextField sno;
    //学生姓名
    JTextField sname;
    //课程号
    JTextField cno;
    //课程名
    JTextField cname;
    //成绩id
    JTextField id;

    //学生
    JTextField sid;

    //课程ID
    JTextField cid;

    //成绩
    JTextField score;

    JButton clearButton;

    //删除的按钮
    JButton deleButton;

    JButton saveButton;


    private final static String DEFAULT_File_Path = "upload/no_pic.gif";

    private void initColumns() {
        this.columns = new Vector();
        this.columns.add("id");
        this.columns.add("学号");
        this.columns.add("姓名");
        this.columns.add("课程编号");
        this.columns.add("课程");
        this.columns.add("成绩");

    }


    public ScorePanel() {

        setViewDatas();
        initColumns();

        //设置列表
        DefaultTableModel model = new DefaultTableModel(getDatas(), this.columns);
        JTable table = new CommonJTable(model);
        setJTable(table);

        JScrollPane upPane = new JScrollPane(table);
        upPane.setPreferredSize(new Dimension(1000, 350));

        //设置添加, 修改的界面
        JPanel downPane = new JPanel();
        downPane.setLayout(new BoxLayout(downPane, BoxLayout.X_AXIS));

        Box downBox1 = new Box(BoxLayout.X_AXIS);
        //添加id隐藏域
        id = new JTextField(10);
        id.setVisible(false);
        downBox1.add(id);
        //列表下面的box


        /***************************************************/
        Box downBox4 = new Box(BoxLayout.X_AXIS);

        downBox4.add(new JLabel("学号："));
        downBox4.add(Box.createHorizontalStrut(10));

        sno = new JTextField(10);
        downBox4.add(sno);
        downBox4.add(Box.createHorizontalStrut(30));


        downBox4.add(new JLabel("姓名："));
        downBox4.add(Box.createHorizontalStrut(10));

        sname = new JTextField(20);
        downBox4.add(sname);
        downBox4.add(Box.createHorizontalStrut(30));

        Box downBox5 = new Box(BoxLayout.X_AXIS);
        downBox5.add(new JLabel("课程号："));

        cno = new JTextField(10);
        downBox5.add(cno);
        downBox5.add(Box.createHorizontalStrut(30));


        downBox5.add(new JLabel("课程名："));

        cname = new JTextField(20);
        downBox5.add(cname);
        downBox5.add(Box.createHorizontalStrut(30));

        /*******************************************************/

        Box downBox2 = new Box(BoxLayout.X_AXIS);
        downBox2.add(new JLabel("成绩："));
        downBox2.add(Box.createHorizontalStrut(10));

        score = new JTextField(10);
        downBox2.add(score);
        downBox2.add(Box.createHorizontalStrut(30));
        /*******************************************************/
        Box downBox3 = new Box(BoxLayout.X_AXIS);

        saveButton = new JButton("保存");
        downBox3.add(saveButton);
        downBox3.add(Box.createHorizontalStrut(30));

        deleButton = new JButton("删除");
        downBox3.add(deleButton);
        downBox3.add(Box.createHorizontalStrut(30));

        clearButton = new JButton("清空");
        downBox3.add(clearButton);
        downBox3.add(Box.createHorizontalStrut(30));

        /*******************************************************/
        Box downLeftBox = new Box(BoxLayout.Y_AXIS);

        downLeftBox.add(getSplitBox());
        downLeftBox.add(downBox1);
        downLeftBox.add(getSplitBox());
        downLeftBox.add(downBox4);
        downLeftBox.add(getSplitBox());
        downLeftBox.add(downBox5);
        downLeftBox.add(getSplitBox());
        downLeftBox.add(downBox2);
        downLeftBox.add(getSplitBox());
        downLeftBox.add(downBox3);


        Box downRightBox = new Box(BoxLayout.Y_AXIS);

        //downRightBox.add(p);

        downPane.add(downLeftBox);
        downPane.add(downRightBox);


        JPanel queryPanel = new JPanel();
        Box queryBox = new Box(BoxLayout.X_AXIS);


        queryBox.add(Box.createHorizontalStrut(30));

        queryPanel.add(queryBox);
        this.add(queryPanel);

        //列表为添加界面
        JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, upPane, downPane);
        split.setDividerSize(5);
        this.add(split);
        //添加监听器
        initListeners();
    }

    private void initListeners() {
        //表格选择监听器
        getJTable().getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent event) {
                //当选择行时鼠标释放时才执行
                if (!event.getValueIsAdjusting()) {
                    //如果没有选中任何一行, 则返回
                    if (getJTable().getSelectedRowCount() != 1)
                        return;
                    view();
                }
            }
        });
        //清空按钮监听器
        clearButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                clear();
            }
        });
        //保存按钮监听器
        saveButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //验证空值
                if (sno.getText().trim().equals("")) {
                    showWarn("请输入学号");
                    return;
                }
                if (cno.getText().trim().equals("")) {
                    showWarn("请输入课程号");
                    return;
                }
                if (score.getText().trim().equals("")) {
                    showWarn("请输入成绩");
                    return;
                }
                save();
            }
        });
        //删除按钮监听器
        deleButton.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent arg0) {
                dele();
            }
        });

        // 添加回车键监听
        sno.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String stno = sno.getText().trim();

                if (!stno.isEmpty()) {
                    StudentDao studentDao = new StudentDao();
                    String stname = studentDao.getNameByNo(stno);
                    if(stname==null) {
                        JOptionPane.showMessageDialog(center, "学号错误", "查询失败", JOptionPane.INFORMATION_MESSAGE);
                        sno.setText(null);
                    }
                    else {
                        sname.setText(stname);
                        cno.requestFocus();
                    }
                    // 清空文本框
                } else {
                    JOptionPane.showMessageDialog(center, "请输入学号", "查询失败", JOptionPane.INFORMATION_MESSAGE);
                    System.out.println("未输入任何内容！");
                }
            }
        });

        cno.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String scno = cno.getText().trim();

                if(!scno.isEmpty()){
                    CourseDao courseDao = new CourseDao();
                    String scname = courseDao.getNameByNo(scno);
                    if(scname==null)
                        JOptionPane.showMessageDialog(center, "课程号错误", "查询失败", JOptionPane.INFORMATION_MESSAGE);
                    else {
                        cname.setText(scname);
                        score.requestFocus();
                    }
                    // 清空文本框
                } else {
                    JOptionPane.showMessageDialog(center, "请输入课程号", "查询失败", JOptionPane.INFORMATION_MESSAGE);
                    System.out.println("未输入任何内容！");
                }
            }
        });
    }


    //清空表单, 刷新列表
    public void clear() {
        refreshTable();
        this.id.setText("");
        this.sno.setText("");
        this.sname.setText("");
        this.cno.setText("");
        this.cname.setText("");
        this.score.setText("");
    }

    //保存
	private void save()  {
        StudentDao studentDao = new StudentDao();
        String sno = this.sno.getText();
        String sname = this.sname.getText();
        if (!studentDao.getDataBySno(sno,sname)) {
            showWarn("学号或名字有误");
            return;
        }
//		String sid = student.getId();
        CourseDao courseDao = new CourseDao();
        String cno = this.cno.getText();
        String cname = this.cname.getText();
        if (!courseDao.getDataByCno(cno,cname)) {
            showWarn("课程号或课程名有误");
            return;
        }
        ScoreDao scoreDao = new ScoreDao();
        if(scoreDao.getDataByOne(sno,cname)){
            showWarn("该学生课程已经录入");
            return;
        }
//		String cid = course.getId();
        String tsno = this.sno.getText();
        String tcno = this.cno.getText();
        String tsname = this.sname.getText();
        String tcname = this.cname.getText();
        float tscore = Float.parseFloat(this.score.getText());
        String id = this.id.getText();
        Score score1 = new Score();
        score1.setSno(tsno);
        score1.setSname(tsname);
        score1.setCno(tcno);
        score1.setCname(tcname);
        score1.setScore(tscore
        );

        score1.setId(id);
        ScoreDao score1Dao = new ScoreDao();
        try {
            if(id==null || id.equals("")) {
                score1Dao.insertData(score1);
                JOptionPane.showMessageDialog(center, "保存成功", "成功", JOptionPane.INFORMATION_MESSAGE);
            }else {
                score1Dao.updateData(score1);
                JOptionPane.showMessageDialog(center, "更改成功", "成功", JOptionPane.INFORMATION_MESSAGE);
            }
            setViewDatas();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.print("修改数据失败");
            JOptionPane.showMessageDialog(center, "修改失败", "error", JOptionPane.ERROR_MESSAGE);
        }

		setViewDatas();
		clear();
	}


    //验证输入
    private boolean validateScore() {
        String score = this.score.getText();
        try {
            Integer p = Integer.parseInt(score);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    //修改书本, 修改时不需要修改库存, 因为库存取决于销售与入货
//	private void update() {
//		Book book = getBook();
//		//由于是修改, 因此需要设置id
//		book.setID(this.bookId.getText());
//		bookService.update(book);
//		//重新读取数据
//		setViewDatas();
//		//刷新列表, 清空表单
//		clear();
//	}

    //从界面中获取数据并封装成Score对象
    //private Score getScore() {

//		String score = this.score.getText();
//
//		Student student = (Student)this.studentComboBox.getSelectedItem();
//		Course course = (Course)this.courseComboBox.getSelectedItem();
//		Score sc = new Score();
//		sc.setSid(student.getSid());
//		sc.setCid(course.getCid());
//		sc.setScore(score);
//		return sc;
    //}

    //查看成绩
	private void view() {
		try {
			String id = getSelectId(getJTable());
			ScoreDao scoreDao = new ScoreDao();
			Score sc = scoreDao.getData(id);
			this.id.setText(sc.getId());
			this.sno.setText(sc.getSno());
            this.sname.setText(sc.getSname());
			this.cno.setText(sc.getCno());
            this.cname.setText(sc.getCname());
			this.score.setText(String.valueOf(sc.getScore()));
		}catch(Exception e) {

		}

	}

    /*
     * 实现父类方法, 查询数据库并返回对应的数据格式, 调用父类的setDatas方法设置数据集合
     */
	public void setViewDatas() {
		try {
			ScoreDao scoreDao = new ScoreDao();
			//查找对应的数据
			Vector<Score> scores = (Vector<Score>)scoreDao.getDatas();
			//转换显示格式
			Vector<Vector> datas =  changeDatas(scores);
			//调用父类方法设置结果集合
			setDatas(datas);
            refreshTable();
		}catch(Exception e) {

		}

	}

    //将数据转换成视图表格的格式
	private Vector<Vector> changeDatas(Vector<Score> datas) {
		Vector<Vector> view = new Vector<Vector>();
		for (Score score : datas) {
			Vector v = new Vector();
			v.add(score.getId());
			v.add(score.getSno());
			v.add(score.getSname());
			v.add(score.getCno());
			v.add(score.getCname());
			v.add(score.getScore());
			view.add(v);
		}
		return view;
	}

    @Override
    public Vector<String> getColumns() {
        return this.columns;
    }

    @Override
    public void setTableFace() {
        //隐藏id列
        getJTable().getColumn("id").setMinWidth(-1);
        getJTable().getColumn("id").setMaxWidth(-1);
        //getJTable().getColumn("简介").setMinWidth(350);
        getJTable().setRowHeight(30);
    }



    //创建一个Type对象, 用于添加到下拉框中, 该方法中创建的Type对象重写了toString和equals方法
//	private Student makeStudent(final Student source) {
//		Student student = new Student(){
//			public String toString(){
//				return source.getSname();
//			}
//			public boolean equals(Object obj) {
//				if (obj instanceof Student) {
//					Student t = (Student)obj;
//					if (getId().equals(t.getId())) return true;
//				}
//				return false;
//			}
//		};
//		student.setId(source.getId());
//		return student;
//	}

    //创建一个Concern对象, 用于添加到下拉框中, 该方法中创建的Concern对象重写了toString和equals方法
    //private Course makeCourse(final Course c) {
//		Course course = new Course() {
//			public String toString(){
//				return c.getCname();
//			}
//			public boolean equals(Object obj) {
//				if (obj instanceof Course) {
//					Course co = (Course)obj;
//					if (getCid().equals(co.getCid())) return true;
//				}
//				return false;
//			}
//		};
//		course.setCid(c.getCid());
//		return course;
    //}
    public void dele() {
        String id = this.id.getText();
        if(id==null || id.equals("")) {
            System.out.print("请选择删除的数据");
        }else {
            ScoreDao scoreDao = new ScoreDao();
            try {
                scoreDao.deleData(id);
                JOptionPane.showMessageDialog(center, "删除成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                setViewDatas();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                JOptionPane.showMessageDialog(center, "删除失败", "error", JOptionPane.ERROR_MESSAGE);
                System.out.print("修改删除失败");
            }
        }
    }

}